﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Media.Imaging;

using RaisingStudio.SmallProgram.Library.Internal;

namespace RaisingStudio.SmallProgram.Library
{
    [SmallProgramType]
    public static class Desktop
    {
        public static Primitive Width
        {
            get
            {
                return SystemParameters.PrimaryScreenWidth;
            }
        }

        public static Primitive Height
        {
            get
            {
                return SystemParameters.PrimaryScreenHeight;
            }
        }


        internal static Primitive ConvertToBitmap(Primitive fileNameOrUrl)
        {
            if (fileNameOrUrl.IsEmpty)
            {
                return fileNameOrUrl;
            }
            string localFile = Path.GetTempFileName();
            SmallProgramApplication.Invoke(delegate
            {
                BitmapImage bitmapImage = ImageList.LoadImageFromFile(fileNameOrUrl);
                if (bitmapImage != null)
                {
                    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                    BitmapFrame item = BitmapFrame.Create(bitmapImage);
                    encoder.Frames.Add(item);
                    using (Stream stream = System.IO.File.Create(localFile))
                    {
                        encoder.Save(stream);
                    }
                }
            });
            return new Primitive(localFile);
        }

        public static void SetWallPaper(Primitive fileOrUrl)
        {
            if (!fileOrUrl.IsEmpty)
            {
                string lpvParam = (string)ConvertToBitmap(fileOrUrl);
                NativeHelper.SystemParametersInfo(20, 0, lpvParam, 3);
            }
        }
    }
}

